package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmswms.entity.ShelfOnTask;
import com.sunda.spmswms.entity.ShelfOnTaskDtl;
import com.sunda.spmswms.entity.WhsStorageInventory;
import com.sunda.spmswms.mapper.ShelfOnTaskDtlMapper;
import com.sunda.spmswms.mapper.WhsStorageInventoryMapper;
import com.sunda.spmswms.service.IShelfOnTaskDtlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmswms.service.IWhsOperateLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static com.sunda.spmscommon.Constans.SPARE_PARTS_INTO_STORAGE;

/**
 * <p>
 * 上架任务表明细 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-03-19
 */
@Service
public class ShelfOnTaskDtlServiceImpl extends ServiceImpl<ShelfOnTaskDtlMapper, ShelfOnTaskDtl> implements IShelfOnTaskDtlService {

    @Autowired
    WhsStorageInventoryMapper whsStorageInventoryMapper;

    @Autowired
    IWhsOperateLogService iWhsOperateLogService;

    @Autowired
    WhsStorageInventoryServiceImpl whsStorageInventoryService;

    // 初始化上架、下架任务表明细
    @Override
    public void generateShelfOnTaskDtl(String uuid, String deliveryNoteSap) {
        List<Map<String, Object>> shelfOnTaskDtl = this.baseMapper.getBoxNote(deliveryNoteSap);
        for (int i = 0; i < shelfOnTaskDtl.size(); i++) {
            ShelfOnTaskDtl taskDtl = new ShelfOnTaskDtl();
            taskDtl.setUuid(uuid);
            taskDtl.setTaskRowId(String.valueOf((i + 1) * 10));
            taskDtl.setBoxNote(shelfOnTaskDtl.get(i).get("boxNote").toString());
            taskDtl.setDeliveryNoteSap(deliveryNoteSap);
            /** 上架任务是备件货箱码，数量默认给 1 */
            taskDtl.setQuantity(1.00);
            this.baseMapper.insert(taskDtl);
        }
    }

    /**
     * 完成上架任务,by boxNote 只用于备件
     * uuid 上架任务的uuid
     * storageUuid: "b95946ac1dab42b79ade3438acb0b53a"， 储位uuid
     */
    @Override
    public ResponseResult completeShelfOnTaskDtlByBoxNote(String uuid, JSONArray shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                for (int k = 0; k < shelfOnTaskDtlList.size(); k++) {
                    JSONObject jsonObject = shelfOnTaskDtlList.getJSONObject(k);
                    if (jsonObject.getString("boxNote").equals(boxNote)) {
                        Double boxQtyReceived = jsonObject.getDouble("boxQtyReceived");
                        if (boxQtyReceived > 0) {
                            /*=系统参数有两种情况，有时叫targetStorage， 有时叫storageUuid*/
                            String storageUuid =jsonObject.containsKey("storageUuid")?jsonObject.getString("storageUuid"):jsonObject.getString("targetStorage");
                            shelfOnTaskDtl.setTargetStorage(storageUuid);
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            String deliveryNoteSap = jsonObject.getString("deliveryNoteSap");
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("BOX_NOTE", boxNote));
                            // 更新储位库存
                            ResponseResult result = updateShelfOnTaskDtlX(storageUuid, boxNote, deliveryNoteSap, userId);
                            if (result.getCode() == 200) {
                                // 储位库位扣减成功， 跳出当前的循环
                                break;
                            } else {
                                // 储位库位扣减失败
                                return result;
                            }
                        }else{
                            shelfOnTaskDtl.setTargetStorage("[]");
                            shelfOnTaskDtl.setQuantity(0.0);
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("BOX_NOTE", boxNote));
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by BoxNote[completeShelfOnTaskDtlByBoxNote] ");
        }
    }

    /*  以uuid和rowID为主键完成上架任务， 只用于备件
     *  以储位id与boxNote为主键更新储位库存
     *  "shelfOnTaskDtls": [
     *    {
     *      "uuid": "shelfONTask UUID",
     *      "taskRowId": "10",
     *      "targetStorage": "储位UUID",
     *      "quantity": 1.0
     *    },
     *    {
     *      "uuid": "shelfONTask UUID",
     *      "taskRowId": "20",
     *      "targetStorage": "储位UUID",
     *      "quantity": 1.0
     *    }
     *  ]
     * */
    @Override
    public ResponseResult completeShelfOnTaskDtlByRowID(String uuid, JSONArray shelfOnTaskDtls, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shlfOnDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shlfOnDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shlfOnDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                String taskRowId = shelfOnTaskDtl.getTaskRowId();
                if (StringUtils.isEmpty(boxNote) || StringUtils.isEmpty(taskRowId)) {
                    return ResponseResult.error("box not or taskrowId is blank in this shelfOntask");
                }
                for (int k = 0; i < shelfOnTaskDtls.size(); k++) {
                    JSONObject jsonObject = shelfOnTaskDtls.getJSONObject(k);
                    if (jsonObject.getString("taskRowId").equals(taskRowId)) {
                        Double quantity = jsonObject.getDouble("quantity");
                        String deliveryNoteSap=shelfOnTaskDtl.getDeliveryNoteSap();
                        if (quantity > 0) {
                            String storageUuid = jsonObject.getString("targetStorage");
                            shelfOnTaskDtl.setTargetStorage(storageUuid);
                            shelfOnTaskDtl.setQuantity(quantity);
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("TASK_ROW_ID", taskRowId));
                            // 更新储位库存 备件货
                            ResponseResult result = updateShelfOnTaskDtlX(storageUuid, boxNote, deliveryNoteSap, userId);
                            if (result.getCode() != 200) {
                                // 储位库位扣减失败
                                return result;

                            }
                            // 储位库位扣减成功， 跳出当前的循环
                            break;
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by RowId [completeShelfOnTaskDtlByRowID] ");
        }
    }

    // 按照shelfOnTaskUuid与boxNote完成上架任务，List<ShelfOnTaskDtl> 只用于备件
    @Override
    public ResponseResult completeShelfOnTaskDtlByBoxNote(String uuid, List<ShelfOnTaskDtl> shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    ShelfOnTaskDtl shDtl = shelfOnTaskDtlList.get(k);
                    if (shDtl.getBoxNote().equals(boxNote)) {
                        Double boxQtyReceived = shDtl.getQuantity();
                        if (boxQtyReceived > 0) {
                            shelfOnTaskDtl.setTargetStorage(shDtl.getTargetStorage());
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            String deliveryNoteSap = shDtl.getDeliveryNoteSap();
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("BOX_NOTE", boxNote));
                            // 更新储位库存
                            ResponseResult result = updateShelfOnTaskDtlX(shDtl.getTargetStorage(), boxNote, deliveryNoteSap, userId);

                            if (result.getCode() == 200) {
                                // 储位库位扣减成功， 跳出当前的循环
                                break;
                            } else {
                                // 储位库位扣减失败
                                return result;
                            }
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by BoxNote [completeShelfOnTaskDtlByBoxNote] ");
        }
    }

    // 按照shelfOnTaskUuid与rowId完成上架任务，List<ShelfOnTaskDtl> 只用于备件
    @Override
    public ResponseResult completeShelfOnTaskDtlByRowID(String uuid, List<ShelfOnTaskDtl> shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                String taskRowId = shelfOnTaskDtl.getTaskRowId();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    ShelfOnTaskDtl shDtl = shelfOnTaskDtlList.get(k);
                    if (shDtl.getTaskRowId().equals(taskRowId)) {
                        Double boxQtyReceived = shDtl.getQuantity();
                        if (boxQtyReceived > 0) {
                            shelfOnTaskDtl.setTargetStorage(shDtl.getTargetStorage());
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("TASK_ROW_ID", taskRowId));
                            if (boxNote != null) {
                                // 更新储位库存 备件货
                                ResponseResult result = updateShelfOnTaskDtlX(shDtl.getTargetStorage(), boxNote, shDtl.getDeliveryNoteSap(), userId);
                                if (result.getCode() == 200) {
                                    // 储位库位扣减成功， 跳出当前的循环
                                    break;
                                } else {
                                    // 储位库位扣减失败
                                    return result;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by Row ID [completeShelfOnTaskDtlByRowID] ");
        }
    }

    // 按照shelfONTaskUuid与boxNote完成下架任务 只用于备件
    @Override
    public ResponseResult completeDeductTaskDtlByBoxNote(String uuid, JSONArray shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    JSONObject shDtl = shelfOnTaskDtlList.getJSONObject(k);
                    if (shDtl.getString("boxNote").equals(boxNote)) {
                        Double boxQtyReceived = shDtl.getDouble("boxQtyReceived");
                        if (boxQtyReceived > 0) {
                            shelfOnTaskDtl.setTargetStorage(shDtl.getString("targetStorage"));
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            String deliveryNoteSap = shDtl.getString("deliveryNoteSap");
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("BOX_NOTE", boxNote));
                            // 更新储位库存
                            ResponseResult result = updateDeductTaskDtlX(shDtl.getString("targetStorage"), boxNote, deliveryNoteSap, userId);
                            if (result.getCode() == 200) {
                                // 储位库位扣减成功， 跳出当前的循环
                                break;
                            } else {
                                // 储位库位扣减失败
                                return result;
                            }
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by BoxNote [completeDeductTaskDtlByBoxNote] ");
        }

    }

    // 按照shelfONTaskUuid与rowId完成下架任务  只用于备件
    @Override
    public ResponseResult completeDeductTaskDtlByRowId(String uuid, JSONArray shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shlfOnDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shlfOnDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shlfOnDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                String taskRowId = shelfOnTaskDtl.getTaskRowId();
                String deliveryNoteSap = shelfOnTaskDtl.getDeliveryNoteSap();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    JSONObject jsonObject = shelfOnTaskDtlList.getJSONObject(k);
                    if (jsonObject.getString("taskRowId").equals(taskRowId)) {
                        Double quantity = jsonObject.getDouble("quantity");
                        if (quantity > 0) {
                            String storageUuid = jsonObject.getString("targetStorage");
                            shelfOnTaskDtl.setTargetStorage(storageUuid);
                            shelfOnTaskDtl.setQuantity(quantity);
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("TASK_ROW_ID", taskRowId));
                            if (boxNote != null) {
                                // 更新储位库存 备件货
                                ResponseResult result = updateDeductTaskDtlX(storageUuid, boxNote, deliveryNoteSap, userId);
                                if (result.getCode() == 200) {
                                    // 储位库位扣减成功， 跳出当前的循环
                                    break;
                                } else {
                                    // 储位库位扣减失败
                                    return result;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by Row ID [completeDeductTaskDtlByRowId] ");
        }
    }

    // 按照shelfOnTaskUuid与boxNote完成下架任务，List<ShelfOnTaskDtl>  只用于备件
    @Override
    public ResponseResult completeDeductTaskDtlByBoxNote(String uuid, List<ShelfOnTaskDtl> shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    ShelfOnTaskDtl shDtl = shelfOnTaskDtlList.get(k);
                    if (shDtl.getBoxNote().equals(boxNote)) {
                        Double boxQtyReceived = shDtl.getQuantity();
                        if (boxQtyReceived > 0) {
                            shelfOnTaskDtl.setTargetStorage(shDtl.getTargetStorage());
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            String deliveryNoteSap = shDtl.getDeliveryNoteSap();
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("BOX_NOTE", boxNote));
                            // 更新储位库存
                            ResponseResult result = updateDeductTaskDtlX(shDtl.getTargetStorage(), boxNote, deliveryNoteSap, userId);
                            if (result.getCode() == 200) {
                                // 储位库位扣减成功， 跳出当前的循环
                                break;
                            } else {
                                // 储位库位扣减失败
                                return result;
                            }

                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by BoxNote [completeDeductTaskDtlByBoxNote] ");
        }
    }

    // 按照shelfOnTaskUuid与rowId完成下架任务，List<ShelfOnTaskDtl>  只用于备件
    @Override
    public ResponseResult completeDeductTaskDtlByRowId(String uuid, List<ShelfOnTaskDtl> shelfOnTaskDtlList, String userId) {
        try {
            QueryWrapper<ShelfOnTaskDtl> queryWrapper = new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid);
            List<ShelfOnTaskDtl> shelfOnTaskDtls = this.baseMapper.selectList(queryWrapper);
            // 完成上架任务
            for (int i = 0; i < shelfOnTaskDtls.size(); i++) {
                ShelfOnTaskDtl shelfOnTaskDtl = shelfOnTaskDtls.get(i);
                String boxNote = shelfOnTaskDtl.getBoxNote();
                String taskRowId = shelfOnTaskDtl.getTaskRowId();
                for (int k = 0; i < shelfOnTaskDtlList.size(); k++) {
                    ShelfOnTaskDtl shDtl = shelfOnTaskDtlList.get(k);
                    if (shDtl.getTaskRowId().equals(taskRowId)) {
                        Double boxQtyReceived = shDtl.getQuantity();
                        if (boxQtyReceived > 0) {
                            shelfOnTaskDtl.setTargetStorage(shDtl.getTargetStorage());
                            shelfOnTaskDtl.setQuantity(boxQtyReceived);
                            this.baseMapper.update(shelfOnTaskDtl, new QueryWrapper<ShelfOnTaskDtl>().eq("UUID", uuid).eq("TASK_ROW_ID", taskRowId));
                            if (boxNote != null) {
                                // 更新储位库存 备件货
                                ResponseResult result = updateDeductTaskDtlX(shDtl.getTargetStorage(), boxNote, shDtl.getDeliveryNoteSap(), userId);
                                if (result.getCode() == 200) {
                                    // 储位库位扣减成功， 跳出当前的循环
                                    break;
                                } else {
                                    // 储位库位扣减失败
                                    return result;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when complete ShelfOnTask by Row Id [completeDeductTaskDtlByRowId] ");
        }
    }

    /*
     * 更新储位库存, 上架 只用于备件
     * */
    public ResponseResult updateShelfOnTaskDtlX(String uuid, String boxNote, String deliveryNoteSap, String userId) {
        return whsStorageInventoryService.updateStorageInventoryX(uuid, boxNote, deliveryNoteSap, userId);
    }

    /*
     * 更新储位库存, 下架 只用于备件
     * */

    public ResponseResult updateDeductTaskDtlX(String uuid, String boxNote, String deliveryNoteSap, String userId) {
        return whsStorageInventoryService.updateDeductTaskDtlX(uuid, boxNote, deliveryNoteSap, userId);
    }

}
